import { getSts } from '@/service/common'
import type { IOssModel } from './browserUpload'
import miniUpload from './miniAppUpload'

class UploadUtil {
  public static async uploadImages(filePaths: string[], api = getSts): Promise<string[]> {
    return new Promise<string[]>((resolve, reject) => {
      // request<IOssModel>('/api/common/ai-sts', 'POST', null)
      api()
        .then(async (res) => {
          const ossInfo = res.data
          const resultList: string[] = []
          for (const imagePath of filePaths) {
            const url = await this.uploadImage(imagePath, ossInfo).catch((err) => reject(err))

            if (url) resultList.push(url)
          }
          if (resultList.length === filePaths.length) {
            resolve(resultList)
          } else {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject({ message: '上传失败' })
          }
        })
        .catch((e) => {
          reject(e)
        })
    })
  }

  /**
   * 上传本地图片数组，返回本地路径对应的oss路径
   * @param filePaths 本地路径
   * @param api 鉴权
   * @returns map key:本地路径  value:oss路径
   */
  public static async uploadImagesToMap(
    filePaths: string[],
    api: () => Promise<any>,
  ): Promise<Map<string, string>> {
    return new Promise<Map<string, string>>((resolve, reject) => {
      api()
        .then(async (res) => {
          const ossInfo = res.data
          const resultMap = new Map<string, string>()
          for (const imagePath of filePaths) {
            const url = await this.uploadImage(imagePath, ossInfo).catch((err) => reject(err))
            if (url) resultMap.set(imagePath, url)
          }
          if (resultMap.size === filePaths.length) {
            resolve(resultMap)
          } else {
            // eslint-disable-next-line prefer-promise-reject-errors
            reject({ message: '上传失败' })
          }
        })
        .catch((e) => {
          reject(e)
        })
    })
  }

  private static async uploadImage(filePath: string, ossInfo: IOssModel): Promise<string> {
    let result = ''
    // #ifdef H5
    const module = await import('./browserUpload')
    result = await module.default(filePath, ossInfo)
    // #endif
    if (result.length <= 0) {
      result = await miniUpload(filePath, ossInfo)
    }
    return result
  }
}

export default UploadUtil
